<template>

    <view>
        <view v-if="openid==''" style="text-align: center;">
            <u-loading mode="circle"></u-loading>
        </view>
        <view v-if="openid!=''">
            <view class="order-price-view">
                <view>
                    <custom-price class="u-margin-top-30" :price="order.need_pay_price" :size="60" :fontWeight="400"></custom-price>
                    <view>
                        <text class="times-title">支付剩余时间</text>
                        <u-count-down :timestamp="cancel_left_time" :show-days="false"></u-count-down>
                    </view>
                </view>
            </view>

            <view class="payment-view u-margin-top-30">
                <view class="u-p-25">
                    <u-checkbox active-color="#FA3534" v-model="isCheckPreDeposit" :disabled="!(account_balance > 0)" shape="square">
                        <view class="u-m-l-10 u-font-24">
                            <text>使用预存款支付（预存款余额￥{{account_balance | unitPrice}}，目前还需在线支付￥{{ order.need_pay_price | unitPrice}}）余额不足？</text>
                            <text @click="handleRecharge">马上充值</text>
                        </view>
                    </u-checkbox>
                    <view class="" v-if="isCheckPreDeposit">
                        <u-message-input active-color="#FA3534" :maxlength="6" :dot-fill="true" @finish="handlePasswordFinish"></u-message-input>
                        <view class="tip-box">
                            <view class="u-flex">
                                <u-icon size="36" name="error-circle-fill"></u-icon>
                                <text class="u-font-24 u-m-l-10">支付密码与用户登录密码不同，可在用户中心进行设置</text>
                            </view>
                            <navigator class="tip" url="/mine-module/account-safe" v-if="!order.deposite.is_pwd">您还未设置支付密码?</navigator>
                            <navigator class="tip" url="/mine-module/account-safe" v-else>忘记密码?</navigator>
                        </view>
                    </view>
                </view>
            </view>

            <view class="payment-view u-margin-top-30">
                <view class="u-flex u-row-between u-p-25" :class="index > 0 ? 'cell-view' : '' " @click="handlePaymentType(pay.plugin_id)" v-for="(pay, index) in paymentList" :key="index">
                    <view class="cell-icon">
                        <u-image width="200" height="60" :src="pay.image"></u-image>
                    </view>
                    <view class="cell-title">
                        {{ pay.method_name }}
                    </view>
                    <view class="cell-right-icon">
                        <u-icon :name="pay.selected ? 'xuanze' : 'choose'" custom-prefix="custom-icon"></u-icon>
                    </view>
                </view>
            </view>

            <view class="big-btn" @click="handlePayment" v-if="!isCheckPreDeposit">
                <view class="btn u-flex u-row-center">
                    确认支付
                    <custom-price :price="order.need_pay_price" :textColor="'#FFFFFF'"></custom-price>
                </view>
            </view>

            <!-- #ifdef H5 -->
             <div class="__pay_form__"></div>
            <!-- #endif -->
            <view v-if="debug">{{log}}</view>
       </view>
       <!-- 进入加载 -->
       <loading-view v-if="loading"></loading-view>
    </view>
</template>

<script>
    import * as API_Trade from '@/api/trade.js'
    import * as Payment from '@/common/payment.js'
    import * as API_Deposit from '@/api/deposit.js'
    import * as Openid from '@/api/openid.js'
    import Cache,{Keys} from '@/utils/cache.js';

    export default {
        data() {
            return {
                debug:false, //在app里显示调试日志
                openid:'',
                log:'log',
                trade_sn: '',
                order_sn: '', //订单编号
                order: '', //订单详情
                is_callback:'',//是否是支付跳转回来的，如果为yes，表示是跳转回来的
                default_plugin_id:'', //默认要选中的支付方式
                paymentList: [], //支付方式列表
                payment_plugin_id: '' ,//支付方式
                cancel_left_time: '',//剩余支付时间
                account_balance: 0, //预存款余额
                isCheckPreDeposit: false, //是否使用预存款支付
                loading: true,
                noClick: true //禁止多次点击
            };
        },
        onLoad(options) {
            this.trade_sn = options.trade_sn || ''
            this.order_sn = options.order_sn || ''
            this.is_callback = options.is_callback || ''
            this.default_plugin_id = options.default_plugin_id || ''
            this.openid= Cache.getItem(Keys.wxopenid);

            if(this.is_callback=='yes'){
                this.payCallback()
            }

            // #ifdef APP-PLUS
            this.openid = 'appopenid'
            this.loadPaymentList()
            // #endif

            // #ifdef H5
            let code=options.code || ''
            this.loadH5OpenId(code)
            // #endif


            // #ifdef MP-WEIXIN
            this.loadMiniOpenId()
            // #endif

            this.getCancelLeftTime()
        },
        watch: {
            isCheckPreDeposit(val) {
                if (!val) return
                this.paymentList.forEach(item => {
                    item.selected = false
                })
            }
        },
        methods: {
            // 获取订单取消剩余时间
            getCancelLeftTime() {
                const trade_type = this.trade_sn ? 'TRADE' : 'ORDER'
                const sn = this.trade_sn || this.order_sn
                API_Trade.getCancelLeftTime(trade_type,sn).then(response => {
                    this.cancel_left_time = response
                    this.loading = false
                })
            },
            //马上充值
            handleRecharge() {
                uni.navigateTo({
                    url:"/mine-module/account-balance"
                })
            },
            //支付密码输入结束
            handlePasswordFinish(password) {
                const trade_type = this.trade_sn ? 'TRADE' : 'ORDER'
                const sn = this.trade_sn || this.order_sn
                const params = {
                    sn,
                    trade_type,
                    password
                }
                API_Deposit.getBalancePay(trade_type, sn, params).then(response => {
                    if(response.need_pay == 0) {
                        uni.redirectTo({
                            url:"/order-module/payment-complete/payment-complete"
                        })
                    } else {
                        this.isCheckPreDeposit = false
                        this.password = ''
                        this.loadPaymentList()
                    }
                })
            },
            loadMiniOpenId(){
                if(this.openid==''){
                     Openid.fetchWeixinMiniOpenId().then(openid=>{
                          this.openid= openid
                          this.loadPaymentList()
                     }).catch(e=>{
                         this.$u.toast(`获取openid出现意外错误`)
                     })
                }else{
                      this.loadPaymentList()
                }

            },
            loadH5OpenId(code){

                //非微信内部，跳过获取openid
                if (!this.is_weixin()){
                    this.openid="h5openid"
                }
                if(this.openid==''){

                    console.log("code is "+ code)
                    if(code==''){
                        Openid.createRedirectUri().then(url=>{

                             location.href=url;
                        });
                    }else{
                        Openid.fetchWeiXinH5OpenId(code).then(openid=>{
                             this.openid= openid
                             this.loadPaymentList()
                        })
                    }

                }else{
                      this.loadPaymentList()
                }

            },
            is_weixin(){
                let ua = navigator.userAgent.toLowerCase();
                if(ua.match(/MicroMessenger/i)=="micromessenger") {
                    return true;
                } else {
                    return false;
                }
            },
            loadPaymentList(){
                // #ifdef APP-PLUS
                const client_type = 'NATIVE'
                // #endif
                // #ifdef H5
                const client_type = 'WAP'
                // #endif
                // #ifdef MP
                const client_type = 'MINI'
                // #endif
                Promise.all([
                    this.trade_sn
                        ? API_Trade.getCashierData({ trade_sn: this.trade_sn })
                        : API_Trade.getCashierData({ order_sn: this.order_sn }),
                    API_Trade.getPaymentList(client_type),
                    API_Deposit.getDepositBalance()
                ]).then(response => {
                    this.order = response[0];
                    this.account_balance = response[2];
                    if(response[1] && response[1].length) {
                        // 默认不选中支付方式
                        response[1].forEach(item => {
                            item.selected = false;
                            //如果传递了default_plugin_id则选中此支付方式
                            if(item.plugin_id == this.default_plugin_id){
                                 item.selected = true;
                            }
                        })
                        this.paymentList = response[1];
                        // #ifndef MP-WEIXIN
                        // 如果是在微信浏览器内则隐藏支付宝支付
                        if(this.is_weixin()) {
                            this.paymentList = this.paymentList.filter(item => item.plugin_id !== 'alipayDirectPlugin');
                        }
                        // #endif

                        // 如果是在小程序内则隐藏支付宝支付
                        // #ifdef MP-WEIXIN
                        console.log('this is MP-WEIXIN')
                        this.paymentList = this.paymentList.filter(item => item.plugin_id !== 'alipayDirectPlugin')
                        // #endif
                    }

                    if(this.default_plugin_id==''){
                        this.paymentList[0].selected=true
                        this.payment_plugin_id =  this.paymentList[0].plugin_id
                    }else{
                        this.payment_plugin_id =this.default_plugin_id
                    }

                })
            },
            //选择支付方式
            handlePaymentType(plugin_id) {
                this.paymentList.forEach(item => {
                    item.selected = false
                    if(item.plugin_id === plugin_id) {
                        item.selected = true
                    }
                })
                this.payment_plugin_id = plugin_id
            },
            payCallback() {
                uni.showModal({
                    title: '支付提示',
                    content: '请确认支付是否完成',
                    confirmText: '支付成功',
                    cancelText: '重新支付',
                    success(res) {
                        if(res.confirm) {
                            uni.redirectTo({
                                url: '/order-module/order/order-list'
                            })
                        }
                    }
                })
            },
            payFail(err){
                if(this.debug){
                     this.log='fail:' + JSON.stringify(err)
                }
            },
            //确定支付
            handlePayment() {
                // 防止连续点击
                this.$u.throttle(this.initiatePay, 2000)
            },
            async initiatePay() {
                if(this.openid=='error'){
                    this.$u.toast(`openid不正确，不能支付`)
                    return
                }
                if (!this.paymentList.some(item => item.selected)) {
                    this.$u.toast(`请选择支付方式`)
                    return
                }
                const trade_type = this.trade_sn ? 'trade' : 'order'
                const sn = this.trade_sn || this.order_sn
                const openid= this.openid;
                // #ifdef APP-PLUS
                const client_type = 'NATIVE'
                // #endif

                // #ifdef H5
                const client_type = 'WAP'
                // #endif


                // #ifdef MP
                const client_type = 'MINI'
                // #endif

                const pay_mode = 'normal'
                const payment_plugin_id = this.payment_plugin_id
                const that = this

                // #ifdef H5
                const uni_app = 'H5'
                // #endif

                // #ifndef H5
                const uni_app = 'UNH5'
                // #endif

                if (this.noClick) {
                    this.noClick = false
                    API_Trade.initiatePay(trade_type, sn, {
                        client_type,
                        pay_mode,
                        uni_app,
                        payment_plugin_id,
                        openid
                    }).then(response => {
                        if (payment_plugin_id === 'weixinPayPlugin') {

                            //微信内嵌H5，调用wechatH5Pay方法
                            // #ifdef H5
                            if (typeof WeixinJSBridge == "undefined"){
                                Payment.mobileH5Pay(response,this.payCallback,this.payFail)
                            }else{
                                Payment.wechatH5Pay(response,this.payCallback,this.payFail)
                            }
                            // #endif

                            //微信小程序，调用wechatMiniPay方法
                            // #ifdef MP-WEIXIN
                            Payment.wechatMiniPay(response,this.payCallback,this.payFail)
                            // #endif

                            //微信App
                            // #ifdef APP-PLUS
                            Payment.wechatAppPay(response,this.payCallback,this.payFail)
                            // #endif

                        } else {
                            // #ifdef H5
                            //调起支付宝支付
                            Payment.aliPayH5(response,this.payCallback,this.payFail)
                            // #endif
                            // #ifdef APP-PLUS
                            Payment.aliPayApp(response,this.payCallback,this.payFail)
                            // #endif
                        }
                    })
                    setTimeout(()=> {
                        that.noClick= true;
                    }, 1500)
                }
            }
        }
    }
</script>

<style lang="scss">
    .order-price-view {
        background-color: #FFFFFF;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 50rpx;
        text-align: center;
        .order-price {
            font-size: 45rpx;
            color: #FA3534;
            font-weight: bold;
        }
        .times-title {
            margin: 0rpx 10rpx;
        }
    }
    .payment-view {
        margin: 20rpx;
        border-radius: 20rpx;
        background-color: #FFFFFF;
        .cell-view {
            border-top: 2rpx solid #E5E5E5;
        }
        .cell-icon {
            padding: 10rpx 0rpx;
        }
        .cell-title {
            text-align: right;
            flex: 1;
            margin: 0 20rpx;
            font-size: 30rpx;
            font-weight: bold;
        }
    }
    .tip-box {
        padding-left: 20rpx;
        margin-top: 20rpx;
        color: #ffcc00;
        .tip {
            display: inline-block;
            background-color: #F59C1A;
            border-color: #F59C1A;
            color: #FFF;
            padding: 8rpx 16rpx;
            border-radius: 10rpx;
            margin: 20rpx 0 0 10rpx;
            font-size: 24rpx;
        }
    }
    /deep/ {
        .custom-icon-xuanze {
            color: #FA3534;
            font-size: 40rpx !important;
        }
        .custom-icon-choose {
            font-size: 40rpx !important;
        }
    }
</style>

